import {RequestMethod} from "../lib/defines";
import {Room} from "../lib/Rooms";
import {ChatModeEnums} from "../utils/enums";

export default function join (app) {
  const { socket, rooms: lRooms } = app.locals;
  const { userId } = socket.handshake.query;

  socket.on(RequestMethod.join, async function(data, cb) {
    const { room: { classId }, uri } = data;
    const { clientUtils, client } = app.locals;
    const __room: Room = lRooms[classId];

    if (!__room) {
      return cb && cb({status: 'error', message: 'room not find!'})
    }

    if (!__room.members[userId]) {
      __room.setMember(socket.owner)
    }

    // console.log('==============> ', room)

    // 加入 临时房间
    socket.join(classId);

    const pipeline = await clientUtils.createMediaPipeline(client);
    __room.members[userId].pipeline = pipeline;

    /**
     * URL 广播
     *
     * 单独处理
     */
    if (__room.chatMode === ChatModeEnums.BROADCAST && uri) {
      __room.members[userId].player = await clientUtils.createPlayerEndpoint(pipeline, uri);
    }

    const endpoint = await clientUtils.createEndpoint(pipeline);
    __room.members[userId].setEndpoint(userId, endpoint);

    clientUtils.onIceCandidate(endpoint, (iceCandidate) => {
      socket.emit('iceCandidate', {
        iceCandidate,
        member: socket.owner
      });
    });

    // 回调
    if (cb) {
      cb({
        status: 'ok',
        resolve: 'joined',
        members: __room.getMembers(),
        room: __room.json(),
      })
    }
  });
}
